<template>
    <div class="boxWrapper early-wrapper">
        <div class="add">
            <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAddMsg" v-if="permissions.showRoleAdd">新增计划</el-button>
        </div>
        <el-table :data="tableList" stripe  height="calc(100vh - 180px)">
        <el-table-column align="center" label="计划名" prop="planName" />
        <el-table-column align="center" label="预警类型" prop="tp">
          <template slot-scope="scope">
            <el-tag type="success" size="small" v-if="scope.row.tp == 1">测点预警</el-tag>
            <el-tag type="primary" size="small" v-if="scope.row.tp == 2">指标预警</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="发送时间" prop="times"/>
        <el-table-column align="center" label="创建人" prop="createUserName"/>
        <el-table-column align="center" label="创建时间" prop="CreateTime"/>
        <el-table-column align="center" label="指标设置" prop="CreateTime">
          <template slot-scope="scope">
            <div v-if="scope.row.tp == 2">
              <span style="margin-right: 6px;">{{ scope.row.linK_POINT_NAME }}</span>
              <el-button type="primary" size="mini" icon="el-icon-s-tools" @click="handleSetPoint(scope.row)" circle style="padding:5px;"></el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-link type="primary" icon="el-icon-edit" @click="handleEditList(scope.row)" :underline="false" v-if="permissions.showRoleEdit">编辑</el-link>
            <el-link type="danger" icon="el-icon-delete" @click="handleDelList(scope.row)" style="margin-left:12px" :underline="false" v-if="permissions.showRoleDel">删除</el-link>
          </template>
        </el-table-column>
      </el-table>


      <el-dialog title="计划配置" :visible.sync="msgDialogVisible" width="500px" :before-close="handleCloseDialog" v-dialogDrag>
        <el-form ref="dialogForm" :model="dialogForm" label-width="90px" size="medium">
          <el-form-item label="计划名">
            <el-input v-model="dialogForm.planName" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="预警类型">
            <el-select v-model="dialogForm.tp" placeholder="请选择">
              <el-option label="测点预警" :value="1"></el-option>
              <el-option label="指标预警" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发送时间">
            <el-select v-model="dialogForm.times" placeholder="请选择" multiple>
              <el-option label="即时发送" value="-1"></el-option>
              <el-option label="0点" value="0"></el-option>
              <el-option label="1点" value="1"></el-option>
              <el-option label="2点" value="2"></el-option>
              <el-option label="3点" value="3"></el-option>
              <el-option label="4点" value="4"></el-option>
              <el-option label="5点" value="5"></el-option>
              <el-option label="6点" value="6"></el-option>
              <el-option label="7点" value="7"></el-option>
              <el-option label="8点" value="8"></el-option>
              <el-option label="9点" value="9"></el-option>
              <el-option label="10点" value="10"></el-option>
              <el-option label="11点" value="11"></el-option>
              <el-option label="12点" value="12"></el-option>
              <el-option label="13点" value="13"></el-option>
              <el-option label="14点" value="14"></el-option>
              <el-option label="15点" value="15"></el-option>
              <el-option label="16点" value="16"></el-option>
              <el-option label="17点" value="17"></el-option>
              <el-option label="18点" value="18"></el-option>
              <el-option label="19点" value="19"></el-option>
              <el-option label="20点" value="20"></el-option>
              <el-option label="21点" value="21"></el-option>
              <el-option label="22点" value="22"></el-option>
              <el-option label="23点" value="23"></el-option>
              <el-option label="24点" value="24"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="推送人员">
            <el-select v-model="dialogForm.smS_Plan_Users" multiple placeholder="请选择">
              <el-option
                v-for="item in userList"
                :key="item.uid"
                :label="item.name"
                :value="item.uid">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="btnGroup">
          <el-button @click="handleCloseDialog" icon="el-icon-circle-close" size="small">取消</el-button>
          <el-button type="primary" @click="handleSaveData" icon="el-icon-circle-check" size="small">保存</el-button>
        </div>
      </el-dialog>


      <el-dialog title="指标" :visible.sync="listDialog" width="900px" :before-close="handleCancelList" v-dialogDrag>
          <div class="dialog-wrapper">
              <div class="tree-box" style="width:400px">
                <el-tree :data="indexMenuList" default-expand-all>
                  <div class="custom-tree-node" slot-scope="{ node, data }">
                    <span @click="handleIndexTreeClick(data,false)" class="treeName">{{ data.indeX_NAME }}</span>
                      <el-checkbox v-model="data.choosed" :true-label="1" :false-label="0" @change="handleChangeChoosed($event,data)" class="treeSelect"></el-checkbox>
                  </div>
                </el-tree>
              </div>
              <div class="dialog-right" v-if="menuIndex !== ''">
                  <el-form :model="listForm[menuIndex]" label-width="80px" ref="listForm" v-if="listForm.length > 0">
                    <el-form-item label="分量"  prop="COMPS" v-if="isBottom == 1">
                      <el-select v-model="listForm[menuIndex].COMPS" placeholder="请选择" multiple style="width:380px">
                        <el-option
                          v-for="item in compList"
                          :key="item.id"
                          :label="item.comP_NAME"
                          :value="item.comp">
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="等级"  prop="LV_criteria">
                      <el-select v-model="listForm[menuIndex].LV_criteria" placeholder="请选择" style="width:380px">
                        <el-option
                          v-for="item in levelList"
                          :key="item.level"
                          :label="item.JUDGEMENT"
                          :value="item.level">
                        </el-option>
                      </el-select>
                    </el-form-item>
                </el-form>
              </div>
          </div>
          <div  class="btnGroup">
              <el-button @click="handleCancelList" size="small" icon="el-icon-circle-close">取 消</el-button>
              <el-button type="primary" @click="handleSaveList" size="small" icon="el-icon-circle-check">保存</el-button>
          </div>
      </el-dialog> 

    </div>
</template>
<script>
import bus from '@/utils/eventBus.js';
import {smsplanList,GetSMSPlanUsers,smsplanAdd,GetPlanById,smsplanDel,getIndexMenu,getIndexSetedMenu,getLevelByID,getCompsSMS,setIndexMenu } from '@/api/https'
import permissionMixin from '@/utils/permission.js'
export default({
    name:'earlyWarning',
    mixins: [permissionMixin],
    data() {
        return {
            stationId:sessionStorage.getItem('stationId'),
            tableList:[],
            formInline:{},
            msgDialogVisible:false,
            dialogForm:{},
            userList:[],
            PlanID:'',
            listDialog:false,
            listForm:[],
            isBottom:0,
            stationData: [],
            showPointSelect:false,
            indexMenuList:[],
            menuIndex:'',
        }
    },
    mounted(){
        this.initBasin()
        this.getList()
    },
    computed: {
        permissions() {
            return this.getPermissions() || {}
        }
    },
    activated(){
       this.initBasin()
        const newStationId = sessionStorage.getItem("stationId");
        if (this.stationId != newStationId) {
             this.stationId = newStationId;
             this.getList()
        }
    },
    deactivated(){
        bus.$off('station-changed', this.handleStationChanged);
    },
    beforeDestroy(){
        bus.$off('station-changed', this.handleStationChanged);
    },
    methods:{
        initBasin() {
            bus.$emit('showBasin', true);
            bus.$off('station-changed', this.handleStationChanged);
            bus.$on('station-changed', this.handleStationChanged);
        },
        handleStationChanged(newStationId, targetRoute) {
            if (!targetRoute || targetRoute === this.$route.name) {
                this.stationId = newStationId;
                this.getList()
            }
        },
        getList(){
            smsplanList({
                planName:'',
                station_ID:this.stationId,
                startTime:'',
                endTime:'',
                pageIndex:1,
                pageSize:100
            }).then(res=>{
                if(res.isSuccess){
                    this.tableList = res.data.data || []
                }else{
                    this.tableList = []
                }
            })
        },
        handleCloseDialog(){
            this.msgDialogVisible = false
            this.dialogForm = {}
        },
        handleAddMsg(){
            this.msgDialogVisible = true
            this.dialogForm = {}
            if(this.userList.length == 0){
                this.handleGetSMSPlanUsers()
            }
        },
        handleGetSMSPlanUsers(){
            GetSMSPlanUsers({
                stationId:this.stationId
            }).then(res=>{
                if(res.isSuccess){
                    this.userList = res.data
                }else{
                    this.userList = []
                }
            })
        },
        handleSaveData(){
            const list = []
            if(this.dialogForm.smS_Plan_Users && this.dialogForm.smS_Plan_Users.length > 0){
                this.dialogForm.smS_Plan_Users.forEach(item=>{
                    list.push({
                        uid:item,
                        PlanID:this.dialogForm.PlanID || 0
                    })
                })
            }
            const data = {
                PlanID:this.dialogForm.PlanID || 0,
                planName:this.dialogForm.planName,
                tp:this.dialogForm.tp,
                Station_ID:this.stationId,
                smS_Plan_Users:list || [],
                times:this.dialogForm.times ? this.dialogForm.times.join(',') : ''
            }
            smsplanAdd(data).then(res=>{
                if(res.isSuccess){
                    this.handleCloseDialog()
                    this.getList()
                }
            })
        },
        handleEditList(data){
            if(this.userList.length == 0){
                this.handleGetSMSPlanUsers()
            }
            GetPlanById({
                id:data.PlanID
            }).then(res=>{
                if(res.isSuccess){
                let data = {}
                let list = []
                const _d = {...res.data}
                if(_d && _d.smS_Plan_Users && _d.smS_Plan_Users.length > 0 ){
                    _d.smS_Plan_Users.forEach(item=>{
                        list.push(item.uid)
                    })
                }
                data = {
                    smS_Plan_Users:[...list],
                    planName:_d.planName,
                    CreateTime:_d.CreateTime,
                    CreateUser:_d.CreateUser,
                    PlanID:_d.PlanID,
                    Station_ID:this.stationId,
                    createUserName:_d.createUserName,
                    tp:_d.tp,
                    times:_d.times ? _d.times.split(',') : ''
                }
                this.dialogForm = {...data}
                this.msgDialogVisible = true
                }
            })
        },
        handleDelList(data){
            this.$confirm(`确认删除名称为${data.planName}的计划？`,'提示',{
                type:'warning'
            }).then(() => {
                smsplanDel({
                    ID:data.PlanID
                }).then(res=>{
                    if(res.isSuccess){
                        this.getList()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }).catch(() => {}); 
        },
        handleSetPoint(data){
            this.PlanID = data.PlanID
            this.listForm = []
            this.handleGetIndexMenu()
            this.listDialog = true
        },
        handleCancelList(){
            this.listForm = []
            this.listDialog = false
            this.PlanID = ''
            this.showPointSelect = false
            this.isBottom = 0
        },
        handleGetIndexMenu(){
            getIndexMenu({
                PlanID:this.PlanID
            }).then(res=>{
                if(res.isSuccess){
                    this.indexMenuList = res.data.data || []
                }
            })
            getIndexSetedMenu({
                PlanID:this.PlanID
            }).then(res=>{
                if(res.isSuccess && res.data && res.data.length > 0){
                    this.menuIndex = ''
                    const list = []
                    res.data.forEach(item=>{
                        const d = {
                        COMPS:item.COMPS !== '' ? item.COMPS.split(',') : [],
                        ID:item.ID,
                        INDEX_ID:item.INDEX_ID,
                        LV_criteria:item.LV_criteria || null,
                        PlanID:item.PlanID,
                        operation:item.operation
                        }
                        list.push(d)
                    })
                    this.listForm = [...list]
                }
            })
        },
        handleSaveList(){
            const list = []
            if(this.listForm.length > 0){
                this.listForm.forEach(item=>{
                const d = {
                    ID:0,
                    PlanID:this.PlanID,
                    INDEX_ID:item.INDEX_ID,
                    COMPS:item.COMPS.join(','),
                    LV_criteria:item.LV_criteria || null,
                    operation:item.operation,
                }
                list.push(d)
                })
            }
            setIndexMenu(list).then(res=>{
                if(res.isSuccess){
                    this.$message.success('设置成功！')
                    this.handleCancelList()
                }else{
                this.$message.error(res.errorMessage)
                }
            })
        },
        handleIndexTreeClick(data,isSelect){
            this.INDEX_ID = data.indeX_ID
            this.isBottom = data.iS_BOTTOM
            if(!isSelect){
                const index = this.listForm.findIndex(item=>item.INDEX_ID == data.indeX_ID)
                if(index > -1){
                this.menuIndex = index
                }else{
                this.listForm.push({
                    ID:0,
                    PlanID:this.PlanID,
                    INDEX_ID:data.indeX_ID,
                    COMPS:[],
                    LV_criteria:'',
                    operation:2,
                })
                data.choosed = 1
                this.menuIndex = this.listForm.length - 1
                }
            }
            this.getDialogRight()
        },
        getDialogRight(){
            getCompsSMS({
                PlanID:this.PlanID,
                INDEX_ID:this.INDEX_ID
            }).then(res=>{
                if(res.isSuccess){
                this.compList = res.data.data
                if(res.data.choosedArr && res.data.choosedArr.length > 0){
                    this.listForm[this.menuIndex].COMPS = res.data.choosedArr
                }
                }
            })

            getLevelByID({
                PlanID:this.PlanID,
                INDEX_ID:this.INDEX_ID
            }).then(res=>{
                if(res.isSuccess){
                this.levelList = res.data.data
                if(res.data.choosedArr && res.data.choosedArr.length > 0){
                    this.listForm[this.menuIndex].LV_criteria = res.data.choosedArr[0]
                }
                }
            })
        },
        handleChangeChoosed(val,data){
            if(val == 1){
                this.listForm.push({
                    ID:0,
                    PlanID:this.PlanID,
                    INDEX_ID:data.indeX_ID,
                    COMPS:[],
                    LV_criteria:'',
                    operation:2,
                })
                this.menuIndex = this.listForm.length - 1
                this.handleIndexTreeClick(data,true)
            }else{
                const index = this.listForm.findIndex(item=>item.INDEX_ID == data.indeX_ID)
                this.menuIndex = ''
                this.listForm.splice(index,1)
            }
        }
    }
})
</script>
<style scoped lang="scss">
.early-wrapper{
    padding:10px;
    box-sizing: border-box;
}
.add{
    display: flex;
    flex-direction: row;
    justify-content: end;
    margin-bottom: 10px;
}
.dialog-wrapper{
  display: flex;
  flex-direction: row;
  justify-content: start;
  .tree-box{
    width:350px;
    max-height: 500px;
    overflow: auto;
    .title{
      font-size: 14px;
      font-weight: bold;
      line-height: 35px;
    }
  }
  
}
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: start;
    .treeName{
      flex: 1;
    }
    .treeSelect{
      margin-right: 10px;
    }
  }
</style>
